﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Phone.Controls;

/**
 * 创建时间：2014/11/28 17:28:27
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace ComicIsland.Common
{
    public class Helper
    {
        public static string UriEscapeDataString(string content)
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                return string.Empty;
            }
            else
                return Uri.EscapeDataString(content);
        }

        public static void SetPageHeight(double actualHeight, Grid element)
        {
            if (actualHeight > 800)
                element.Margin = new Thickness(0, 0, 0, 56);
            else
                element.Margin = new Thickness(0, 0, 0, 72);
        }

        /// <summary>
        /// 16进制转argb颜色
        /// <para>#c1dc23写成#ffc1dc23，其中前两位ff是透明度</para>
        /// </summary>
        /// <param name="colorName"></param>
        /// <returns></returns>
        public static Color HexToColor(string colorName)
        {
            if (colorName.StartsWith("#"))
                colorName = colorName.Replace("#", string.Empty);
            int v = int.Parse(colorName, System.Globalization.NumberStyles.HexNumber);
            return new Color()
            {
                A = Convert.ToByte((v >> 24) & 255),
                R = Convert.ToByte((v >> 16) & 255),
                G = Convert.ToByte((v >> 8) & 255),
                B = Convert.ToByte((v >> 0) & 255)
            };
        }

        /// <summary>
        /// 生成随机因子
        /// <para>循环中生成随机数时必用</para>
        /// </summary>
        /// <returns></returns>
        public int GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }

        /// <summary>
        /// 获取指定字节长度的中英文混合字符串
        /// </summary>
        public string GetString(string s, int length, string apostrophCharacter = "...")
        {
            string result = string.Empty;
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(s);
            if (bytes.Length > length)
            {
                int n = 0;  //  表示当前的字节数 
                int i = 0;//  要截取的字节数
                for (; i < bytes.GetLength(0) && n < length; i++)
                {
                    //  偶数位置，如0、2、4等，为UCS2编码中两个字节的第一个字节
                    if (i % 2 == 0)
                    {
                        n++; //  在UCS2第一个字节时n加1
                    }
                    else
                    {
                        //  当UCS2编码的第二个字节大于0时，该UCS2字符为汉字，一个汉字算两个字节
                        if (bytes[i] > 0)
                        {
                            n++;
                        }
                    }
                }
                //  如果i为奇数时，处理成偶数
                if (i % 2 == 1)
                {
                    if (bytes[i] > 0)//  该UCS2字符是汉字时，去掉这个截一半的汉字
                        i = i - 1;
                    else//  该UCS2字符是字母或数字，则保留该字符
                        i = i + 1;
                }
                result = string.Concat(Encoding.Unicode.GetString(bytes, 0, i), apostrophCharacter);
            }
            else
            {
                result = s;
            }
            return result;
        }

        /// <summary>
        /// 查找某类型的子元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static IEnumerable<T> FindChildren<T>(DependencyObject parent) where T : class
        {
            var count = VisualTreeHelper.GetChildrenCount(parent);
            if (count > 0)
            {
                for (var i = 0; i < count; i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    var t = child as T;
                    if (t != null)
                        yield return t;

                    var children = FindChildren<T>(child);
                    foreach (var item in children)
                        yield return item;
                }
            }
        }

        public static List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : System.Windows.FrameworkElement
        {
            DependencyObject child = null;
            List<T> childList = new List<T>();

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);

                if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
                {
                    childList.Add((T)child);
                }

                childList.AddRange(GetChildObjects<T>(child, ""));
            }
            return childList;
        }

        /// <summary>
        /// 查找父控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T FindParentOfType<T>(DependencyObject obj) where T : FrameworkElement
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);
            while (parent != null)
            {
                if (parent is T)
                {
                    return (T)parent;
                }
                parent = VisualTreeHelper.GetParent(parent);
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sender"></param>
        /// <param name="lls"></param>
        public static void PageShowDataNoMore<T>(object sender, LongListSelector lls) where T : class
        {
            try
            {
                T selectedItem = (sender as System.Windows.Controls.Grid).DataContext as T;
                if (selectedItem == null)
                    return;
                int selectedIndex = lls.ItemsSource.IndexOf(selectedItem);
                int total = lls.ItemsSource.Count;
                //如果是最后一页了并且用户是从最后4条数据往上拉才会提示
                if (total - selectedIndex > 4)
                    return;

                MessageToastManager.Show("没有更多的数据了!");
            }
            catch { }
        }

        /// <summary>
        /// 将Stream转成byte[]
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        /// <summary> 
        /// 将byte[]转成Stream
        /// </summary> 
        public Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }


        public static Dictionary<string, string> GetQueryString(string queryString)
        {
            queryString = queryString.Replace("?", "");
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(queryString))
            {
                int count = queryString.Length;
                for (int i = 0; i < count; i++)
                {
                    int startIndex = i;
                    int index = -1;
                    while (i < count)
                    {
                        char item = queryString[i];
                        if (item == '=')
                        {
                            if (index < 0)
                            {
                                index = i;
                            }
                        }
                        else if (item == '&')
                        {
                            break;
                        }
                        i++;
                    }
                    string key = null;
                    string value = null;
                    if (index >= 0)
                    {
                        key = queryString.Substring(startIndex, index - startIndex);
                        value = queryString.Substring(index + 1, (i - index) - 1);
                    }
                    else
                    {
                        key = queryString.Substring(startIndex, i - startIndex);
                    }

                    result[key] = value;
                    if ((i == (count - 1)) && (queryString[i] == '&'))
                    {
                        result[key] = string.Empty;
                    }
                }
            }
            return result;
        }

        #region ******************************16进制转换******************************
        /// <summary> 
        /// 字符串转16进制字节数组 
        /// </summary> 
        /// <param name="hexString"></param> 
        /// <returns></returns> 
        private static byte[] HexStrToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary> 
        /// 字节数组转16进制字符串 
        /// </summary> 
        /// <param name="bytes"></param> 
        /// <returns></returns> 
        public static string ByteToHexStr(byte[] bytes)
        {
            string result = string.Empty;
            try
            {
                if (bytes != null)
                {
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        result += bytes[i].ToString("X2");
                    }
                }
            }
            catch { }
            return result;
        }

     
        #endregion 16进制转换


        /// <summary>
        /// 元素手势滑动方向
        /// </summary>
        public enum GestureDirection
        {
            None = 0,
            /// <summary>
            /// 从左往右移动
            /// </summary>
            FromLeftToRight = 10,
            /// <summary>
            /// 从右往左移动
            /// </summary>
            FromRightToLeft = 20,
            /// <summary>
            /// 从下往上移动
            /// </summary>
            FromDownToUp = 30,
            /// <summary>
            /// 从上往下移动
            /// </summary>
            FromUpToDown = 40
        }


        public enum SrnOrientation
        {
            Portrait,
            Landscape
        }

        public enum ScrollPageModel
        {
            ScrollUp,
            ScrollDown
        }

        public enum UserGender
        {
            Male = 1,
            Female = 2
        }

        public enum UserLoginType
        {
            Logout = 0,
            Login = 1
        }

        public enum ThirdPlatform
        {
            None = 0,
            QQ = 1,
            SinaWeibo = 2
        }
    }
}
